﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using nRoute.Components.Composition;
using System.IO.IsolatedStorage;
using nRoute.ApplicationServices;
using nRoute.Components.Messaging;
using nRoute.Components;
using nRoute.Mapping;

namespace nRoute.Samples.SquareAway.Services
{
    [MapService(typeof(IHighScoreService), LifetimeManagerType = typeof(SingletonLifetimeManager))]
    public class HighScoreService 
        : IHighScoreService
    {
        private const string HIGH_SCORE_KEY = "SQUAREAWAY_HIGH_SCORE_KEY";

        private int? _highestRecordedScore;
        private IDisposable _subscriptionToken;

        public HighScoreService()
        {
            _subscriptionToken = Channel.GetChannel<Object>("ExitInfo").Subscribe(OnApplicationExiting);
            
            if (IsolatedStorageSettings.ApplicationSettings.Contains(HIGH_SCORE_KEY))
            {
                _highestRecordedScore = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings[HIGH_SCORE_KEY]);
            }            
        }

#region Channel Handler

        private void OnApplicationExiting(Object flag)
        {
            IsolatedStorageSettings.ApplicationSettings.Save();
            _subscriptionToken.Dispose();
        }

#endregion

#region IHighScoreService Implementation

        public void RegisterLastScore(int score)
        {
            if (score > _highestRecordedScore.GetValueOrDefault(-1))
            {
                IsolatedStorageSettings.ApplicationSettings[HIGH_SCORE_KEY] = score;                
                _highestRecordedScore = score;
            }
        }

        public int? GetHighestScore()
        {
            return _highestRecordedScore;
        }

#endregion

    }
}